<template>
  <div class="head_box">
    <div class="content">
      <el-row :gutter="20" align="middle">
        <el-col :span="16" :xs="12">
          <div class="logo">
            <a href="/"><img src="@/assets/logo.svg" alt="logo"></a>

            <ul class="nav">
              <li v-for="(item,i) in menu" :key="i" >
                <router-link :to="{path:item.hash}">{{item.name}}</router-link> 
              </li>
            </ul>
          </div>
        </el-col>
        <el-col :span="8" :xs="12">
          <div class="flex_r">
            <div v-if="!address" @click="onWeb()" class="connect">Connect</div>
            <!-- <div v-if="$store.state.address" class="connect address">
              {{ this.$utils.sliceAdd($store.state.address)}}
            </div> -->
            <div v-if="address" class="disconnect">
              <div>
                <p class="add">{{ this.$utils.sliceAdd(address)}}</p>
                <span v-if="changeId == '0x1' || changeId == '0x3'" class="add">{{changeId=='0x3'?'Ropsten':'Main'}} Network</span>
                <span v-if="changeId && changeId != '0x1' && changeId != '0x3'" class="add red">Unsupported Network</span>
              </div>
              
              <div @click="onDisConnect()" class="connect">
                Disconnect
              </div>
            </div>
          </div>
          
        </el-col>
      </el-row>
    </div>

    <div v-if="showerr" class="network_err">
      <img src="@/assets/img/err.svg" alt="" srcset="">
      <h3>Unsupported Network</h3>
      <p>Please change your dapp browers to Mainnet，Ropsten</p>
    </div>
  </div>

  <div class="eth_header_mobile" v-if="this.isMobile">
    <el-drawer
      size="50%"
      direction="ltr"
      v-model="this.isMobile"
      :with-header="false">
      <div class="nav_mb">
        <ul>
            <li v-for="(item,i) in menu" :key="i" :class="isHighlight(item.hash)?'up':''">
                <router-link :to="{path:item.hash}"><el-icon> <Menu /> </el-icon> {{item.name}}</router-link>
            </li>
        </ul>
      </div>
    </el-drawer>
  </div>
    
</template>

<script>
import { Menu } from '@element-plus/icons'
import Abi7 from '@/assets/abi/contract7.json'
import Abi6 from '@/assets/abi/contract6.json'
import Abi5 from '@/assets/abi/contract5.json'
import Abi4 from '@/assets/abi/contract4.json'
import Abi3 from '@/assets/abi/contract3.json'

export default {
  data(){
    return{
        menu:[
            {name:"Domains",hash:'/'},
            {name:"Account",hash:'/account'},
            {name:"Favourites",hash:'/favourites'},
            {name:"About",hash:'/about'},
        ],
        isMobile:false,
        address:null,
        changeId:null,
        showerr:false
    }
  },
   async mounted(){
    if(!window.web3js){
      this.$utils.loadWeb3();
    }
    if(!window.contract7){
      window.contract7 = this.$utils.loadContract(Abi7,'0x869e9b2A879c793C9ae7B39F0c7d370348f9b3Dc')
    }
    if(!window.contract6){
      window.contract6 = this.$utils.loadContract(Abi6,'0x7FF9e009803d8B23a2A5EA19483b59B335Bf41e1')
    }
    if(!window.contract5){
      window.contract5= this.$utils.loadContract(Abi5,'0x4cB85A6d2AEE4F336e08a70ebAC07001C712B128')
    }
    if(!window.contract4){
      window.contract4= this.$utils.loadContract(Abi4,'0xA2d6Bb256c9F3DecfE3618841852fF521fA405e6')
    }
    if(!window.contract3){
      window.contract3= this.$utils.loadContract(Abi3,'0x2d69DA61179e076F51645216316Ce161FA97F14a')
    }
    

    // console.log(this.$store.state)
    // if(!this.$store.state.address){
    //   let isConnect = localStorage.getItem('connect')
    //   console.log('isConnect')
    //   console.log(isConnect)
    //   if(isConnect){
    //     return
    //   }
    //   let accounts = await window.web3js.eth.getAccounts()
    //   // this.$store.dispatch('add_actions', accounts[0] && accounts[0].toLocaleLowerCase());
    //   this.$store.commit('setAddress',accounts[0] && accounts[0].toLocaleLowerCase())
    // }
    if(window.ethereum){

      this.address = localStorage.getItem('address') || null
      // console.log(window.ethereum.selectedAddress,'window.ethereum.selectedAddress')

      this.changeId = await window.ethereum.request({ method: 'eth_chainId' });

      // if(changeId == '0x3'){
      //   this.changeId = 'Ropsten Network'
      // }else if(changeId == '0x1'){
      //   this.changeId = 'Main Network'
      // }else{
      //   this.changeId = changeId
      //   if(this.changeId){
      //     alert('Please change your dapp browser to Ropsten')
      //   }
      // }
      window.ethereum.on('accountsChanged',(val)=>{
        // console.log(val)
        this.address = val[0]
        if(this.address){
          this.$store.commit('setAddress',this.address.toLocaleLowerCase())
        }
        // location.reload()
      })

      window.ethereum.on('chainChanged',(val)=>{
        // this.address = val[0]
        this.changeId = val
        console.log('chainChanged',val)
        // location.reload()
      })
    }


  },
  methods:{
    isHighlight(str){
        if(window.location.hash.indexOf(str) > 0){
            return true
        }else{
            return false
        }
    },
    onDisConnect(){
      this.address = null
      this.$store.commit('setAddress',null)
    },
    // web3
    async onWeb(){
      this.address = await this.$utils.getAccount()
      // console.log(this.address)
      if(this.address){
        this.$store.commit('setAddress',this.address.toLocaleLowerCase())
        this.changeId = await window.ethereum.request({ method: 'eth_chainId' });
      }else{
        this.$store.commit('setAddress',null)
      }
    },
  },
  components:{
      Menu
  },
  watch:{
    changeId:function(val){
      if(val){
        if((val == '0x3') || (val == '0x1')){
          this.showerr = false
        }else{
            this.showerr = true
            setTimeout(async()=>{
              await window.ethereum.request({
                  method: 'wallet_switchEthereumChain',
                  params: [
                      {
                          chainId: window.web3js.utils.numberToHex(3) //链id
                      }
                  ]
              })
            },2000)
            // console.log((window as any).ethereum.chainId)
            // alert('Please change your dapp browser to Ropsten or Main')
        }
      }
    },
    address:function(val){
      this.$store.commit('setAddress',val || null)
    }
  }
}
</script>

<style lang="less" scoped>
.network_err{
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: #ddd;
  z-index: 10000;
  text-align: center;
  img{
    margin: 100px auto 20px;
  }
  h3{
    margin-bottom: 10px;
  }
}
  .head_box{padding: 25px 15px;}
  .logo{
    display: flex;
    align-items: center;
    img{width: auto;height: 30px;margin-right: 50px;}
  }
  
  .nav{
    display: flex;
    justify-content: center;
    align-items: center;
    li{padding-right:15px;color: #fff;}
    a{color: #2481E2;font-weight: 600;padding: 10px 20px;
    border-radius: 30px;box-sizing: border-box;border: 2px solid #f4f4f4;transition: .5s;}
    a:hover,.link-active{
      background: #fff;
      border: 2px solid #2481E2;
    }
  }

  .login{color: #333;background: #fff;padding:5px 10px ;border-radius: 40px;font-size: 10px;font-weight: bold;}
  .meun{height: 18px;margin-left: 20px;cursor: pointer;}

  .address{padding: 12px 15px;}
  .disconnect{
    display: flex;
    align-items: center;
    p{
      width: 120px;
      font-size: 15px;
      font-weight: 600;
      letter-spacing: 1px;
    }
    span{
      position: relative;
      padding-left: 12px;
      color: #aaa;
      font-size: 13px;
      &::before{
        position: absolute;
        left: 0;
        top: 50%;
        width: 5px;
        margin-top: -2.5px;    
        height: 5px;
        content: '';
        background: #2481E2;
        border-radius: 50%;
      }
    }
    .red{
      &::before{
        background: #ec533f;
      }
    }
    .connect{
      margin-left: 10px;
      color: #EFC170;
      border:1px solid #EFC170;
      background: none;
    }
  }

  .eth_header_mobile ul li{
        line-height: 40px;
        .el-icon{margin-right: 5px;}
        a{
            width: 100%;
            color: #fff;
            font-size: 13px;
            display: flex;
            align-items: center;
        }
    }

  @media screen and (max-width:992px ) and (min-width:768px) {
    .nav li{
        padding: 0 10px;
    }
  }
</style>
